package com.chhuang.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chhuang.bean.RegeditAccountBean;
import com.chhuang.bean.ResetPasswordBean;
import com.chhuang.component.I18nMessage;
import com.chhuang.constants.MConstants;
import com.chhuang.core.bean.SaResult;
import com.chhuang.core.enums.SaCode;
import com.chhuang.core.exception.SaException;
import com.chhuang.email.bean.EmailCaptcha;
import com.chhuang.model.ChUser;
import com.chhuang.service.ChUserService;
import com.chhuang.utils.digest.Md5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName RegeditController
 * @Description 用户注册
 * @Author Darren Huang
 * @Date 2022/11/20 11:23
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/regedit")
@Api(value = "用户注册", tags = "用户注册接口")
public class RegeditController {

    /**
     * 获取国际化资源组件
     */
    @Resource
    private I18nMessage i18nMessage;

    @Resource
    private ChUserService chUserService;

    /**
     * 用户注册接口
     * @param regeditAccount
     * @return
     */
    @PostMapping
    @ApiOperation(value = "用户注册接口", notes = "用户注册接口")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "用户注册成功")
    })
    public SaResult<Void> regedit(@Validated @RequestBody RegeditAccountBean regeditAccount){
        //验证校验码
        String sessionId = regeditAccount.getCaptchaBean().getSessionId();
        if(SaSessionCustomUtil.isExists(sessionId)) {
            SaSession saSession = SaSessionCustomUtil.getSessionById(sessionId);
            EmailCaptcha emailCaptcha = (EmailCaptcha) saSession.get(MConstants.SESSION_EMAIL_CAPTCHA_KEY);
            if (emailCaptcha == null || !emailCaptcha.getEmail().equals(regeditAccount.getEmail())
                    || !emailCaptcha.getCode().equalsIgnoreCase(regeditAccount.getCaptchaBean().getCaptcha())) {
                throw new SaException(SaCode.LOGIN_CAPTCHA_FAIL);
            }
        }else {
            throw new SaException(SaCode.LOGIN_CAPTCHA_FAIL);
        }

        if(chUserService.exists(Wrappers.<ChUser>lambdaQuery().eq(ChUser::getUsername, regeditAccount.getUsername())))
            throw new SaException(SaCode.REGEDIT_USERNAME_ALREADY_EXISTS);
        if(chUserService.exists(Wrappers.<ChUser>lambdaQuery().eq(ChUser::getPhone, regeditAccount.getPhone())))
            throw new SaException(SaCode.REGEDIT_PHONE_ALREADY_EXISTS);
        if(chUserService.exists(Wrappers.<ChUser>lambdaQuery().eq(ChUser::getEmail, regeditAccount.getEmail())))
            throw new SaException(SaCode.REGEDIT_EMAIL_ALREADY_EXISTS);

        SaSessionCustomUtil.deleteSessionById(sessionId); //删除session

        ChUser user = new ChUser();
        BeanUtil.copyProperties(regeditAccount, user);
        user.setPassword(Md5Util.md5(user.getPassword(), user.getUsername()));
        Date now = new Date();
        user.setCreateTime(now);
        user.setModifyTime(now);

        if(chUserService.save(user)) {
            return SaResult.ok(i18nMessage.get(SaCode.SUCCESS.getCode()));
        }else {
            return SaResult.error(i18nMessage.get(SaCode.SAVE_FAIL.getCode()));
        }
    }

    /**
     * 根据邮箱重置密码 修改密码
     * @param resetPasswordBean
     * @return
     */
    @ApiOperation(value = "重置密码接口", notes = "重置密码接口")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "重置密码成功")
    })
    @PostMapping("/resetPassword")
    public SaResult<Void> resetPassword(@Validated @RequestBody ResetPasswordBean resetPasswordBean) {
        //验证校验码
        String sessionId = resetPasswordBean.getCaptchaBean().getSessionId();
        if(SaSessionCustomUtil.isExists(sessionId)) {
            SaSession saSession = SaSessionCustomUtil.getSessionById(sessionId);
            EmailCaptcha emailCaptcha = (EmailCaptcha) saSession.get(MConstants.SESSION_EMAIL_CAPTCHA_KEY);
            if (emailCaptcha == null || !emailCaptcha.getEmail().equals(resetPasswordBean.getEmail())
                    || !emailCaptcha.getCode().equalsIgnoreCase(resetPasswordBean.getCaptchaBean().getCaptcha())) {
                throw new SaException(SaCode.LOGIN_CAPTCHA_FAIL);
            }
        }else {
            throw new SaException(SaCode.LOGIN_CAPTCHA_FAIL);
        }
        SaSessionCustomUtil.deleteSessionById(sessionId); //删除session

        //修改密码
        ChUser chUser = chUserService.getOne(Wrappers.<ChUser>lambdaQuery().eq(ChUser::getEmail, resetPasswordBean.getEmail()), false);
        chUser.setPassword(Md5Util.md5(resetPasswordBean.getPassword(), chUser.getUsername()));
        chUser.setModifyTime(new Date());

        chUserService.updateById(chUser);

        return SaResult.ok(i18nMessage.get(SaCode.SUCCESS.getCode()));
    }
}
